import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:image_picker/image_picker.dart';
// import 'dart:io';
import 'bottom_sheet.dart';

enum PickImageType {
  gallery,
  camera,
}

// 图片选择的类
class UploadImageModel {
  final PickedFile imageFile;
  final int imageIndex;

  UploadImageModel(this.imageFile, this.imageIndex);
}

// 上传的控件
class UploadImageItem extends StatelessWidget {
  final GestureTapCallback onTap; // 点击事件
  final Function callBack; // 点击后的回调
  final UploadImageModel imageModel; // 选择的图片
  final Function deleteFun; // 删除的方法
  UploadImageItem({this.onTap, this.callBack, this.imageModel, this.deleteFun});
  @override
  Widget build(BuildContext context) {
    return Container(
        width: 80,
        height: 80,
        child: Stack(
          alignment: Alignment.topRight,
          children: <Widget>[
            Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(3),
                    color: Color(0xFFF0F0F0)),
                child: imageModel == null
                    ? InkWell(
                        onTap: onTap ??
                            () {
                              BottomActionSheet.show(context, [
                                '相机',
                                '相册',
                              ], callBack: (i) {
                                callBack(i);

                                return;
                              });
                            },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Center(
                              child: Icon(
                                Icons.camera_alt,
                                color: ColorUtil.color("#33000000"),
                                size: 30,
                              ),
                            ),
                            Text(
                              '点击添加照片',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 11, color: Color(0xff999999)),
                            )
                          ],
                        ))
                    : Image.asset(
                        imageModel.imageFile.path,
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.cover,
                      )),
            Positioned(
              top: 0,
              right: 0,
              child: Offstage(
                offstage: (imageModel == null),
                child: InkWell(
                  highlightColor: Colors.transparent,
                  splashColor: Colors.transparent,
                  child: Container(
                    width: 16,
                    height: 16,
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.circular(8)),
                    child: Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 14,
                    ),
                  ),
                  onTap: () {
                    print('点击了删除');
                    if (imageModel != null) {
                      deleteFun(this);
                    }
                  },
                ),
              ),
            ),
          ],
        ));
  }
}

class UcarImagePicker extends StatefulWidget {
  final String title; // 标题
  final int maxCount; //允许上传的图片个数
  final ValueChanged<String> onChanged; // 选择图片之后的回调函数给父组件
  final imgUrl; //数据回显的时候的图片链接

  UcarImagePicker({this.title, this.maxCount = 1, this.onChanged, this.imgUrl});
  @override
  _UcarImagePickerState createState() => _UcarImagePickerState();
}

class _UcarImagePickerState extends State<UcarImagePicker> {
  List _images = []; //保存添加的图片
  int currentIndex = 0; //当前图片的下标
  bool isDelete = false; // 是否删除
  final picker = ImagePicker(); // 图片选择对象
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _images..add(UploadImageItem(
      callBack: (int i) {
        if (i == 0) {
          _getImage(PickImageType.camera);
        } else {
          _getImage(PickImageType.gallery);
        }
      },
    ));
  }

  _getImage(PickImageType type) async {
    var image = await picker.getImage(
        source: type == PickImageType.gallery
            ? ImageSource.gallery
            : ImageSource.camera);
    UploadImageItem();
    setState(() {
      // 存图片地址
      print('add image at $currentIndex');
      _images.insert(
          _images.length - 1,
          UploadImageItem(
            imageModel: UploadImageModel(image, currentIndex),
            deleteFun: (UploadImageItem item) {
              print('remove image at ${item.imageModel.imageIndex}');
              bool result = _images.remove(item);
              print('left is ${_images.length}');
              if (_images.length == widget.maxCount - 1 && isDelete == false) {
                isDelete = true;
                _images.add(UploadImageItem(
                  callBack: (int i) {
                    if (i == 0) {
                      _getImage(PickImageType.camera);
                    } else {
                      print('打开相册');
                      _getImage(PickImageType.gallery);
                    }
                  },
                ));
                // 回调给父组件自己选择的图片地址
                widget.onChanged('');
              }
              print('remove result is $result');
              setState(() {});
            },
          ));
      currentIndex++;
      if (_images.length == widget.maxCount + 1) {
        // 回调给父组件自己选择的图片地址
        widget.onChanged(image.path);
        _images.removeLast();
        isDelete = false;
      }
    });
  }

  /*拍照*/
  _takePhoto() async {
    var image = await picker.getImage(source: ImageSource.camera);
    UploadImageItem();
    setState(() {
      _images.insert(
          _images.length - 1,
          UploadImageItem(
            imageModel: UploadImageModel(image, currentIndex),
          ));
    });
  }

  /*相册*/
  _openGallery() async {
    //  var image = await  picker.getImage(source: ImageSource.camera);
    var image = await picker.getImage(source: ImageSource.camera);
    _images.insert(
        _images.length - 1,
        UploadImageItem(
          imageModel: UploadImageModel(image, currentIndex),
        ));

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      color: Colors.white,
      padding: EdgeInsets.only(top: 14, left: 20, bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          // 标题(副标题)
          Row(
            children: [
              Text(
                "${widget.title}",
                style: TextStyle(color: Colors.black, fontSize: 15),
              ),
              Text(
                "（最多${widget.maxCount}张，单张照片不超过5M）",
                style: TextStyle(
                    color: ColorUtil.color("#FF999999"), fontSize: 13),
              )
            ],
          ),
          SizedBox(
            height: 22,
          ),
          Wrap(
            alignment: WrapAlignment.start,
            runSpacing: 10,
            spacing: 10,
            children: List.generate(_images.length, (i) {
              return _images[i];
            }),
          )
        ],
      ),
    );
  }
}
